package com.rmb.util;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;


/**
 * RSA安全编码组件
 * @author admin
 *
 */
public class RsaCoder {
    /**
     * 非对称加密秘钥算法
     */
    private static final String KEY_ALGORITHM = "RSA";
    /**
     * 公钥
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";
    /**
     * 私钥
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    /**
     * RSA秘钥长度  默认1024
     */
    private static final int KEY_SIZE = 1024;
    /**
     * 字节 私钥
     */
    private static  byte[] privateKey;
    /**
     * 字节 公钥
     */
    private static byte[] publicKey ;

    private static String privateKeyString = "30820276020100300d06092a864886f70d0101010500048202603082025c02010002818100820afd22bdd36cb75ef8db1a970d50ca352d57eecaa28779a559f626bf9182f0f986a2ea251f76040616032dc739e8558c0dfdfa82bef0203e8412bb2cb0dcaf7f568f100ce05f7bb239a6a4cbd7c1ed8041ea6f3b0c641c94f71228320584ba871012df218799b09f638478b9233bf594faa22d30d792a46b58459a52a1e1ef02030100010281803f5d97671c542f3f52d9b3f9caecc41723be4a80a2e07b5efd014efe268e82dd64d903fd4fc57abe0f311eaf69ca7fb95f9b59cc7d750890cda59172ff1dd70a3a7dae06661b1b7d5785a5153e4716b6c8fe1e2d8f8afc31e97b29d5a59365379a8949ebdf6543d293ec87a43d63ffa6507aa20dd5995efbdaa28c6198991231024100f8a68afdd0a358e2314d35c47a814b548383e2ce53e3eeff18ee844c8983ff40a0c80a4560efb0ffbd1c8b7092b38d75fa3190798c648b73825b11401a44d09502410085e2fb1bad7ffbad70cd6d992f22f504f4d09217b9eca3e4793810cb2a389cd828f091cd625fbc3fa0da7b0178dc3fcdbb94dc77db9c051ceb80c79d7060b373024100bb8c22da3f3c761666496e7cbc4a399f8d7334e79baf18dda0d887419397d437d30e0f71352495c4cfc7700581219d5997553b3bf301038e248cbbfe35d221e10240237c4785cc74716644d18dccddfb6be98661897714662e022e46b7dcc13204101eb9b44b35599e7156d6d167507b3fc5ed83c4f35797809b6ba7d4405c3aa515024055daef13aa8d7ccc927df4b1013e02a148666fece687a8be06a6c9beccf2055c96e0f0f4911fbdffdcf948a886c9e879a828f9962df0cf60b2bcf1d0a2098a8a";

    private static String publicKeyString = "30819f300d06092a864886f70d010101050003818d0030818902818100820afd22bdd36cb75ef8db1a970d50ca352d57eecaa28779a559f626bf9182f0f986a2ea251f76040616032dc739e8558c0dfdfa82bef0203e8412bb2cb0dcaf7f568f100ce05f7bb239a6a4cbd7c1ed8041ea6f3b0c641c94f71228320584ba871012df218799b09f638478b9233bf594faa22d30d792a46b58459a52a1e1ef0203010001";

    /**
     * 私钥解密
     * @param data 待解密的数据
     * @param key  私钥
     * @return byte[] 解密数据
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data,byte[] key) throws Exception{
        //取的私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //生产私钥对象
        PrivateKey  privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

        //对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        //执行
        return cipher.doFinal(data);
    }

    /**
     * @param data 待加密数据
     * @param key  公钥
     * @return byte[] 加密数据
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data,byte[] key) throws Exception{
        //取的公钥
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //生产公钥对象
        PublicKey  publicKey = keyFactory.generatePublic(keySpec);
        //对数据进行加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        //执行
        return cipher.doFinal(data);
    }

    /**取的私钥
     * @param keyMap 秘钥map
     * @return byte[] 私钥
     */
    public static byte[] getPrivateKey(Map<String,Object> keyMap){
        Key key = (Key)keyMap.get(PRIVATE_KEY);
        return key.getEncoded();
    }

    /**取的公钥
     * @param keyMap 秘钥map
     * @return byte[] 公钥
     */
    public static byte[] getPublicKey(Map<String,Object> keyMap){
        Key key = (Key)keyMap.get(PUBLIC_KEY);
        return key.getEncoded();
    }

    private static Map<String,Object> initKey() throws Exception{
        //实例化秘钥生产器
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        //初始化秘钥生产器
        keyPairGen.initialize(KEY_SIZE);
        //生产秘钥对
        KeyPair keyPair = keyPairGen.generateKeyPair();
        //公钥
        RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
        //秘钥
        RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();

        //封装秘钥
        Map<String,Object> keyMap = new HashMap<>(100);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }


    /**
     * 将16进制字符串还原为字节数组.
     */
    private static final byte[] hexStrToBytes(String s) {
        byte[] bytes;

        bytes = new byte[s.length() / 2];

        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16);
        }

        return bytes;
    }


    /**
     * 本方法使用SHA1withRSA签名算法产生签名
     * @return String 签名的返回结果(16进制编码)。当产生签名出错的时候，返回null。
     */
    public static String generateShaWithRsaSigature(String priKey, String src) {
        try {

            Signature sigEng = Signature.getInstance("SHA1withRSA");

            byte[] priByte = hexStrToBytes(priKey.trim());

            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(priByte);
            KeyFactory fac = KeyFactory.getInstance("RSA");

            RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);
            sigEng.initSign(privateKey);
            sigEng.update(src.getBytes());

            byte[] signature = sigEng.sign();
            return new String(Hex.encodeHex(signature));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 本方法使用SHA1withRSA签名算法验证签名
     *
     * @param
     *            pubKey 验证签名时使用的公钥(16进制编码)
     * @param
     *            sign 签名结果(16进制编码)
     * @param
     *            src 签名的原字符串
     * @return String 签名的返回结果(16进制编码)
     */
    public static boolean verifyShaWithRsaSigature(String pubKey, String sign, String src) {
        try {
            Signature sigEng = Signature.getInstance("SHA1withRSA");

            byte[] pubByte = hexStrToBytes(pubKey.trim());

            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubByte);
            KeyFactory fac = KeyFactory.getInstance("RSA");
            RSAPublicKey rsaPubKey = (RSAPublicKey) fac.generatePublic(keySpec);

            sigEng.initVerify(rsaPubKey);
            sigEng.update(src.getBytes());

            byte[] sign1 = hexStrToBytes(sign);
            return sigEng.verify(sign1);

        } catch (Exception e) {
            return false;
        }
    }


    public static void main(String[] args) throws Exception {

        privateKey = hexStrToBytes(privateKeyString);

        publicKey = hexStrToBytes(publicKeyString);

        String str = "RSA";
        byte[] inputStr = str.getBytes();
        System.out.println("原文：\t"+str);

        //以下是先通过私钥对原始数据进行加密，再进行签名 公钥加密
        byte[] signatures = RsaCoder.encryptByPublicKey(inputStr, publicKey);
        System.out.println("加密后：\t"+Base64.encodeBase64String(signatures));

        //进行数据签名
        String signature = new String(Hex.encodeHex(signatures));
        String sign = generateShaWithRsaSigature(privateKeyString,signature);
        System.out.println("签名值：\t"+sign);

        verifySign(sign,signature);
    }

    /**验证签名
     * @param sign  签名值
     * @param data  加密数据
     * @throws Exception 捕获异常
     */
    private static void verifySign(String sign,String data) throws Exception{
        //验证签名
        boolean flag = verifyShaWithRsaSigature(publicKeyString,sign,data);
        System.out.println("签名状态：\t"+flag);

        if(flag){
            byte[] signatures = hexStrToBytes(data);
            //私钥解密
            byte[] decryptData = RsaCoder.decryptByPrivateKey(signatures, privateKey);
            String decryptStr = new String(decryptData);
            System.out.println("解密后：\t"+decryptStr);
        }

    }
}